<template>
  <div class="app-container calendar-list-container">
    <div class="filter-container">
      <el-input @keyup.enter.native="handleFilter" style="width: 200px;" class="filter-item" placeholder="广告名字"
                v-model="listQuery.name">
      </el-input>
      <el-input @keyup.enter.native="handleFilter" style="width: 200px;" class="filter-item" placeholder="商家名字"
                v-model="listQuery.sellerName">
      </el-input>
      <el-select clearable @change='handleFilter' class="filter-item" style="width: 130px"
                 v-model="listQuery.enable" placeholder="状态">
        <el-option label="停用" value="0">
        </el-option>
        <el-option label="启用" value="1">
        </el-option>
      </el-select>
      <el-button class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">查询</el-button>
      <el-button class="filter-item" style="margin-left: 10px;" @click="handleCreate" type="primary" icon="el-icon-edit">新增</el-button>
      <!--<el-button class="filter-item" type="primary" :loading="downloadLoading" icon="el-icon-download" @click="handleDownload">导出</el-button>-->
    </div>
    <el-table :data="list.slice((currentPage-1)*pageSize,currentPage*pageSize)"
               v-loading.body="listLoading" element-loading-text="Loading" border fit highlight-current-row>
      <el-table-column align="center" label='ID' width="95">
        <template slot-scope="scope">
          {{scope.$index}}
        </template>
      </el-table-column>
      <el-table-column label="商家名字" width="130" align="center">
        <template slot-scope="scope">
          {{scope.row.sellerName}}
        </template>
      </el-table-column>

      <el-table-column label="图片名字" width="130" align="center">
        <template slot-scope="scope">
          {{scope.row.name}}
        </template>
      </el-table-column>
      <!--<el-table-column label="图片" width="150" align="center">
        <template slot-scope="scope">
          <span>{{scope.row.img}}</span>
        </template>
      </el-table-column>-->
      <el-table-column label="广告内容" width="260" align="center">
        <template slot-scope="scope">
          <span>{{scope.row.content}}</span>
        </template>
      </el-table-column>
      <el-table-column label="时间" width="165" align="center">
        <template slot-scope="scope">
          {{scope.row.createTime}}
        </template>
      </el-table-column>
      <el-table-column class-name="status-col" label="状态" width="100" align="center">
        <template slot-scope="scope">
          <el-tag :type="scope.row.enable | statusFilter">{{scope.row.enable === 0 ? '停用' : '启用'}}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="排序" width="80" align="center">
        <template slot-scope="scope">
      {{scope.row.sort}}
      </template>
      </el-table-column>
      <el-table-column label="操作" align="center">
        <template slot-scope="scope">
          <el-button size="mini" type="success" @click="handleUpload(scope.row,'img')">广告图片</el-button>
          <el-button type="primary" @click="handleUpdate(scope.row)" size="mini">修改</el-button>
          <el-button size="mini" type="danger" @click="removeUser(scope.row)" >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <div style="padding-top: 20px;text-align: center">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page=currentPage
        :page-sizes="[10, 20, 30]"
        :page-size=pageSize
        layout="total, sizes, prev, pager, next, jumper"
        :total=total>
      </el-pagination>
    </div>

    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form :rules="rules" ref="dataForm" :model="temp" label-position="right" label-width="80px" style='width: 400px; margin-left:50px;'>

        <el-form-item label="商家" prop="sellerId">
          <el-select class="filter-item"  v-model="temp.sellerId" placeholder="请选择">
            <el-option
              v-for="item in sellerList"
              :key="item.sellerId"
              :label="item.name"
              :value="item.sellerId" >
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="广告名字" prop="name">
          <el-input v-model="temp.name" placeholder="广告名字"></el-input>
        </el-form-item>
        <el-form-item label="广告内容" prop="content">
          <el-input type="textarea" :rows="3" v-model="temp.content" placeholder="广告名字"></el-input>
        </el-form-item>

        <el-form-item label="广告状态" prop="enable">
          <el-select class="filter-item" prop="enable" v-model="temp.enable" placeholder="请选择">
            <el-option
              v-for="item in status"
              :key="item.val"
              :label="item.enable"
              :value="item.val">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="排序" prop="sort">
          <el-input v-model="temp.sort"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button :loading="buttonLoading" v-if="dialogStatus=='create'" type="primary" @click="createData">确认
        </el-button>
        <el-button :loading="buttonLoading" v-else type="primary" @click="updateData">确认</el-button>
      </div>
    </el-dialog>
    <el-dialog :title="imgMap[imgDialogStatus]" :visible.sync="dialogUploadImgVisible">
      <el-upload
        ref="imgUpload"
        action="http://upload.qiniup.com"
        :auto-upload="true"
        list-type="picture-card"
        :on-preview="showPreviewImg"
        :before-upload="beforeUpload"
        :on-success="successUpload"
        :data="qData"
        :file-list="fileList"
        :on-remove="removeImg">
        <i class="el-icon-plus"></i>
      </el-upload>
      <el-dialog :visible.sync="previewImgVisible" append-to-body>
          <img width="100%" :src="dialogImgUrl" alt="">
      </el-dialog>
      <div slot="footer" class="dialog-footer">
      <el-button @click="dialogUploadImgVisible = false">取消</el-button>
      <el-button :loading="buttonLoading" @click="mergeUpload" type="primary">确认</el-button>
    </div>
    </el-dialog>
  </div>
</template>

<style>
  .filter-container {
    padding-bottom: 20px;
  }
</style>

<script>
  import { List, Merge } from '../../api/imgBanner'
  import { dels } from '../../api/imgBanner'
  import { domain, getToken } from '../../api/qiniu'
  import { listToStrs } from '../../utils/strUtil'
  import { List as sellerList } from '../../api/seller'

  export default {
    data() {
      return {
        status: [
          { enable: '停用', val: 0 },
          { enable: '启用', val: 1 }
        ],
        sellerList: null,
        list: null,
        listLoading: true,
        buttonLoading: false,
        listQuery: {
          name: null,
          sellerName: null,
          enable: null
        },
        fileList: [],
        temp: {
          imgBannerId: null,
          sellerId: '',
          sellerName: '',
          name: ' ',
          img: '',
          content: ' ',
          sort: '',
          enable: '',
          crateTime: '',
          updateTime: ''
        },
        qData: {
          token: 'vMgCDi6neP07bVcFtdJ3IW5eLh8XJE-UVZ1-bGdd:iI5lIh-FYeji9VqSN2VLmODLCh8=:eyJzY29wZSI6InRvZ2V0aGVyIiwiZGVhZGxpbmUiOjE1MzAxODM0NTl9',
          key: ''
        },
        dialogFormVisible: false,
        dialogUploadImgVisible: false,
        dialogImgUrl: '',
        previewImgVisible: false,
        dialogStatus: '',
        downloadLoading: false,
        textMap: {
          update: '编辑广告信息：',
          create: '新增广告信息：'
        },
        imgMap: {
          img: '广告图片'
        },
        imgDialogStatus: '',
        rules: {
          sellerId: [{ required: true }],
          sellerName: [{ required: true }],
          name: [{ required: false }],
          img: [{ required: true }],
          content: [{ required: false }],
          sort: [{ required: false }],
          enable: [{ required: true }],
          createTime: [{ required: true }],
          updateTime: [{ required: true }]
        },
        total: 0,
        currentPage: 1,
        pageSize: 10
      }
    },
    filters: {
      statusFilter(status) {
        const statusMap = {
          1: 'success',
          // draft: 'gray',
          0: 'danger'
        }
        return statusMap[status]
      }
    },
    created() {
      this.fetchData()
      getToken().then(res => {
        this.qData.token = res.data
      }).catch(error => {
        console.log(error)
      })
    },
    methods: {
      removeUser: function(user) {
        this.$confirm('确定要删除此广告信息吗?', '提示',
          {
            type: 'warning'
          })
          .then((res) => {
            dels({
              imgBannerId: user.imgBannerId
            })
            this.$notify({
              title: '成功',
              message: '删除成功',
              type: 'success',
              duration: 2000
            })
            this.fetchData()
          })
          .catch(() => {
            this.$message.info('已取消操作!')
          })
      },
      fetchData() {
        this.listLoading = true
        List(this.listQuery.name, this.listQuery.sellerName, this.listQuery.enable).then(response => {
          this.list = response.data
          this.total = response.data.length
          this.currentPage = 1
          this.listLoading = false
        })
      },
      handleSizeChange(val) {
        this.pageSize = val
      },
      handleCurrentChange(val) {
        this.currentPage = val
      },
      initSellers() {
        if (this.sellerList == null) {
          sellerList().then(res => {
            this.sellerList = res.data
          })
        }
      },
      handleFilter() {
        this.fetchData()
      },
      handleCreate() {
        this.resetTemp()
        this.initSellers()
        this.dialogStatus = 'create'
        this.dialogFormVisible = true
      },
      handleUpdate(row) {
        this.initSellers()
        this.temp = Object.assign(this.temp, row)
        this.dialogStatus = 'update'
        this.dialogFormVisible = true
      },
      handleDownload() {

      },
      createData() {
        this.$refs.dataForm.validate((valid) => {
          if (valid) {
            this.buttonLoading = true
            this.temp.sort = 1
            Merge(this.temp).then(res => {
              this.temp = res.data
              this.list.unshift(this.temp)
              this.dialogFormVisible = false
              this.buttonLoading = false
              this.$notify({
                title: '成功',
                message: '创建成功',
                type: 'success',
                duration: 2000
              })
              this.fetchData()
            }).catch(reason => {
              console.log(reason)
              this.buttonLoading = false
            })
          } else {
            console.log('验证失败')
          }
        })
      },
      updateData() {
        this.$refs.dataForm.validate((valid) => {
          if (valid) {
            this.buttonLoading = true
            Merge(this.temp).then(res => {
              this.updateList(this.list, this.temp)
              this.dialogFormVisible = false
              this.buttonLoading = false
              this.$notify({
                title: '成功',
                message: '更新成功',
                type: 'success',
                duration: 2000
              })
            }).catch(reason => {
              console.log(reason)
              this.buttonLoading = false
            })
          }
        })
      },
      updateList(list, temp) {
        for (const v of list) {
          if (this.temp.imgBannerId === v.imgBannerId) {
            const index = this.list.indexOf(v)
            this.list.splice(index, 1, temp)
            break
          }
        }
      },
      updateFileList(list, row) {
        if (this.imgDialogStatus === 'img') {
          if (row.img === null || row.img === '') return
          row.img.split(',').forEach(key => {
            list.push({ name: key, url: domain + key })
          })
        }
      },
      resetTemp() {
        this.temp = {
          imgBannerId: null,
          sellerId: '',
          sellerName: '',
          name: '',
          img: '',
          content: '',
          address: '',
          sort: '',
          enable: '',
          crateTime: '',
          updateTime: ''
        }
      },
      handleUpload(row, status) {
        this.resetTemp()
        this.temp.imgBannerId = row.imgBannerId
        this.imgDialogStatus = status
        this.dialogUploadImgVisible = true
        this.fileList.splice(0, this.fileList.length)// 先清空
        this.updateFileList(this.fileList, row)
      },
      removeImg(file) {
        for (var fn of this.fileList) {
          if (fn.name === file.name) {
            this.fileList.splice(this.fileList.indexOf(fn), 1)
          }
        }
      },
      beforeUpload(file) {
        this.qData.key = new Date().valueOf() + file.name
      },
      successUpload(response, file, fileList) {
        this.fileList.push({ name: file.response.key, url: domain + file.response.key })
        console.log(this.fileList)
      },
      mergeUpload() {
        var imgs = listToStrs(this.fileList)
        var param = {}
        if (this.imgDialogStatus === 'img') {
          param = { imgBannerId: this.temp.imgBannerId, img: imgs }
        }
        Merge(param).then(res => {
          this.temp = res.data
          this.updateList(this.list, this.temp)
          this.dialogUploadImgVisible = false
          this.$notify({
            title: '成功',
            message: '修改成功',
            type: 'success',
            duration: 2000
          })
          this.fetchData()
        })
      },
      showPreviewImg(file) {
        this.dialogImgUrl = file.url
        this.previewImgVisible = true
      }
    }
  }
</script>
